package com.woniu.service.Impl.homePage;

import com.alibaba.fastjson.JSON;
import com.woniu.dao.backpage.GoodsDao;
import com.woniu.dao.homePage.CartsDao;
import com.woniu.dao.homePage.OrderDao;
import com.woniu.dao.homePage.OrdersDetailsTwoDao;
import com.woniu.entity.*;
import com.woniu.service.homePage.ICartsService;
import com.woniu.util.IdWorker;
import com.woniu.util.ResData;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author 周权
 * @data 2023/3/6 11:16
 */
@Service
public class CartsServiceImpl implements ICartsService {

    @Autowired
    CartsDao cartsDao;

    @Autowired
    @Qualifier("xueHua")
    IdWorker idWorker;

    @Autowired
    OrderDao orderDao;

    @Autowired
    GoodsDao goodsDao;

    @Autowired
    OrdersDetailsTwoDao ordersDetailsDao;

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Override
    public ResData<?> queryUserCarts(String phone) {
//        String cartsList= redisTemplate.opsForValue().get("carts:" + phone);
//        if (cartsList != null){
//            List<Carts> carts = JSON.parseArray(cartsList, Carts.class);
//            return new ResData<>().ok(carts);
//        }
        List<Carts> cartsList1 = cartsDao.queryCartsByPhone(phone);
//        redisTemplate.opsForValue().set("carts:" + phone, JSON.toJSONString(cartsList1), 30, TimeUnit.MINUTES);
        return new ResData<>().ok(cartsList1);
    }

    @Override
    public ResData<?> queryCartscount(String phone) {
        Double cartsAmount = cartsDao.queryCartscount(phone);
        CartsTotal cartsTotal = new CartsTotal();
        cartsTotal.setCartsAmount(cartsAmount);
        cartsTotal.setCheckedAmount(cartsAmount);
        return new ResData<>().ok(cartsTotal);
    }

    /**
     * 添加购物车
     *
     * @param carts
     * @return
     */
    private String uuid = UUID.randomUUID().toString();

    @Override
    public ResData<?> addUserCarts(Carts carts) {

        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 10, TimeUnit.SECONDS);
        try {
            if (aBoolean) {
                //2.根据商品id和用户账号 去查购物车信息 实现同样商品数量累加的需求
                Carts carts1 = cartsDao.queryCartsByPhoneAndGoodsId(carts);
                //如果为空就用页面传过来的数量，不为空就相加数量
                carts.setCartsNum(carts1 == null ? carts.getCartsNum()
                        : carts1.getCartsNum() + carts.getCartsNum());

                if (carts1 == null) {
                    //没有就新增购物车
                    cartsDao.addCarts(carts);
                } else {
                    //有就修改
                    cartsDao.updateCartGoodsNum(carts);
                }
                //3.累加之前的购买数量，写入数据库
                return new ResData<>().ok();
            } else {
                addUserCarts(carts);//实现自旋锁，调自己方法
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (uuid.equals(redisTemplate.opsForValue().get("lock"))) {
                redisTemplate.delete("lock");
            }
        }
//     redisTemplate.delete("carts"+carts.getPhone());
        return new ResData<>().ok();
    }

    /**
     * 修改购物车是否点击
     *
     * @param id
     * @return
     */
    @Override
    public ResData<?> updateChecked(Integer id) {
        cartsDao.updateChecked(id);

        return new ResData<>().ok();
    }

    /**
     * 修改购物车商品的购买数量
     */

    public ResData<?> updateCartGoodsNum(Carts carts) {
        cartsDao.updateCartGoodsNum(carts);
        List<Carts> cartsList = cartsDao.queryCartsByPhone(carts.getPhone());
        return new ResData<>().ok(cartsList);
    }

    /**
     * 查询商品凑单页
     *
     * @return
     */
    @Override
    public ResData<?> queryGoodsByPrice() {
        List<Goods> goods = cartsDao.queryGoodsByPrice();
        return new ResData<>().ok(goods);
    }

    @Override
    public ResData<?> deleteCartsGoods(Integer id) {
        cartsDao.deleteCartsGoods(id);
        return new ResData<>().ok();
    }

    @Override
    public ResData<?> updateCount(List<OrdersDetails> ordersDetailsList) {
        for (OrdersDetails ordersDetails : ordersDetailsList) {
            goodsDao.updateCount(ordersDetails.getGoodsNum(), ordersDetails.getGoodsId());
        }
        return new ResData<>().ok();
    }

    /**
     * 下单
     *
     * @param cartsIds
     * @return
     */
    @Override
    public ResData<?> buyOrders(List<Integer> cartsIds) {

        if(CollectionUtils.isEmpty(cartsIds)){
            return new ResData<>(2008,"未选择商品",null);
        }
        //查询勾选的购物车信息
        List<Carts> carts1 = cartsDao.queryUserCartsInfo(cartsIds);

        //获取购买量   大于  库存量的数据
        List<Carts> collect = carts1.stream().filter(e -> e.getCartsNum() > e.getCount())
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(collect)) {

            //所有数据写到订单表，添加订单表
            Integer totalNum = 0;

            for (int i = 0; i < carts1.size(); i++) {
                totalNum += carts1.get(i).getCartsNum();
            }

            Double goodsAmounts = 0.0;
            for (int i = 0; i < carts1.size(); i++) {
                goodsAmounts += carts1.get(i).getTotalPrice();
            }

            String xuehuaId = String.valueOf(idWorker.nextId());
            Orders orders = new Orders();
            orders.setId(xuehuaId);
            orders.setPhone(carts1.get(0).getPhone());
            orders.setGoodsAmounts(goodsAmounts);
            orders.setGoodsNums(totalNum);
            orderDao.insertOrders(orders);

            //添加商品订单明细表
            List<OrdersDetails> ordersDetailsList = new ArrayList<>();
            for (Carts carts : carts1) {
                OrdersDetails ordersDetails = new OrdersDetails();
                ordersDetails.setOrdersId(xuehuaId);
                ordersDetails.setGoodsId(carts.getGoodsId());
                ordersDetails.setGoodsNum(carts.getCartsNum());
                ordersDetails.setGoodsAmount(carts.getTotalPrice());
                ordersDetailsList.add(ordersDetails);
            }



            ordersDetailsDao.insertOrdersDetails(ordersDetailsList);
            cartsDao.deleteCartsBatch(cartsIds);
            return new ResData<>().ok(orders.getId());
        } else {
            return new ResData<>(2007,"所选商品库存不足",null);
        }
    }

}